import { useState, useEffect, useEffectEvent } from "react";
class CreateConnection {
  constructor(roomId) {
    this.connected = false;
    this.roomId = roomId;
    // 添加事件监听器存储
    this.events = {};
  }

  // 实现 on 方法
  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  }

  // 实现 emit 方法
  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach((callback) => callback(data));
    }
  }

  connect() {
    this.connected = true;
    // 发布连接成功事件
    this.emit("connected", this.roomId);
  }

  disconnect() {
    this.connected = false;
  }
}

function ChatRoom() {
  const roomId = "office";
  const [theme, setTheme] = useState("light");
  const [msgs, setMsgs] = useState([]);

  // theme 变化会导致 useEffect 重新执行，造成不必要的重连
  // useEffect(() => {
  //     const connection = new CreateConnection(roomId)
  //     connection.on('connected', () => {
  //         console.log('Connected!', theme)
  //         setMsgs([...msgs, `Connected to ${roomId}`])
  //     })
  //     connection.connect()
  //     return () => connection.disconnect()
  // }, [roomId, theme])

  const onConnected = useEffectEvent(() => {
    console.log("Connected!", theme);
  });

  useEffect(() => {
    const connection = new CreateConnection(roomId);
    connection.on("connected", () => {
      setMsgs([...msgs, `Connected to ${roomId}`]);
      onConnected();
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return (
    <>
      <div>Theme: {theme}</div>
      <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
        Change Theme
      </button>
      <p>Msg List</p>
      <ol>
        {msgs.map((item, key) => (
          <li key={key}>{item}</li>
        ))}
      </ol>
    </>
  );
}

export default ChatRoom;
